﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CobraCms.Core.Content.Interfaces;
using CobraCms.MsSqlContentRepository;
using CobraCms.Core.Content;
using CobraCms.MsSqlContentRepository;

namespace CobraCms.Tests
{
    /// <summary>
    /// Tree Manpulation Tests
    ///
    /// </summary>
    [TestClass]
    public class SqlContentRepositoryTests
    {
        private IContentRepository repo;

        private const int TreeLevels = 3;
        private const int NodesPerLevel = 3;        
        

        private ContentNode CreateContentNode(string nodeName, string parentNodeId)
        {
            var node = new ContentNode();
            node.Id = System.Guid.NewGuid().ToString();
            node.ParentId = parentNodeId;
            node.Name = nodeName;
            return node;
        }

        private void BuildTreeRecursive(ContentNode startNode, string nodeNamePrefix, int nodesPerLevel, int levelsDeep, int currentLevel)
        {
            if (currentLevel > levelsDeep)
                return;

            string currentParentNodeId = startNode == null ? null : startNode.Id;

            for (int i = 1; i <= nodesPerLevel; i++)
            {
                var nodeName = nodeNamePrefix + currentLevel.ToString().PadLeft(3, '0') + i.ToString().PadLeft(3,'0');
                var node = CreateContentNode(nodeName, currentParentNodeId);
                var newNode = repo.SaveContentNode(node);
                if (levelsDeep > 0)
                {
                    BuildTreeRecursive(newNode, nodeNamePrefix, nodesPerLevel, levelsDeep, currentLevel+1);
                }
            }
        }

        [TestInitialize]
        public void Init()
        {
            repo = new ContentRepository();
            repo.ClearRepository();
            BuildTreeRecursive(null, "A", NodesPerLevel, TreeLevels, 1);
            //BuildTreeRecursive(null, "B", 10, 10);
            //BuildTreeRecursive(null, "C", 10, 10);
        }

        [TestMethod]
        public void TreeCreation()
        {
            var rootNodes = repo.SearchContentNodes(new ContentNodeSearchCriteira
            {
                IsRootNode = true
            });
            Assert.AreEqual(NodesPerLevel, rootNodes.Count);
            foreach (var rootNode in rootNodes)
            {
                var childNodes = repo.SearchContentNodes(new ContentNodeSearchCriteira
                {
                    ParentNodeId= rootNode.Id
                });
                Assert.AreEqual(NodesPerLevel, childNodes.Count);
            }
        }
    }
}
